package com.vmove.childtrain.utils;

public class DataBuffer {

    byte head = (byte)0xA5;
    byte foot = (byte)0x5A;
    int pDataLen=14;
    int headPosition=0;
    byte[] dataTemp;
    byte[] data;

    public void parseData(byte[] bt){
        if (bt == null || bt.length <= 0) return;
        data = bt;
        //添加上次剩余的数据到前面
        if (null!=dataTemp && dataTemp.length>0){
            int tempLen = dataTemp.length;
            int len = bt.length + tempLen;
            data = new byte[len];
            System.arraycopy(dataTemp, 0, data, 0, tempLen);
            System.arraycopy(bt, 0, data, tempLen, bt.length);
            this.dataTemp = null;
            headPosition=0;
        }

        //找到包头
        if (data[headPosition]!=head){
            while (data[headPosition]!=head){
                headPosition++;
            }
        }

        //只有前半部分包 保存到缓存中
        if (data.length<data[headPosition+1]){
            dataTemp = new byte[data.length];
            System.arraycopy(data, 0, dataTemp, 0, data.length);
            return ;
        }

        if (data.length<pDataLen) return;

        /**
         * 完整数据包数
         */
        int dataCount = data.length/pDataLen;
        //剩余数据个数
        int dataTempLen = data.length%pDataLen;

        for (int i=0;i<dataCount;i++){
            if (data.length<pDataLen) return;
            byte[] dataR = new byte[pDataLen];
            System.arraycopy(data, headPosition, dataR, 0, pDataLen);
            headPosition+=pDataLen;
            if (null!=dataCallBack)
                dataCallBack.call(dataR);
        }
    }

    CallBack dataCallBack;

    public CallBack getCallBack() {
        return dataCallBack;
    }

    public void setCallBack(CallBack callBack) {
        this.dataCallBack = callBack;
    }

    public interface CallBack {
        void call(byte[] data);
    }

}
